{% extends "base.html" %}
{% block head %}
    <script src="https://cdn.jsdelivr.net/npm/mermaid@10.6.1/dist/mermaid.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/ace/1.32.0/ace.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/ace/1.32.0/ext-language_tools.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/ace/1.32.0/mode-text.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/ace/1.32.0/theme-chrome.js"></script>
    <style>
        .editor-container {
            display: flex;
            height: 70vh;
            gap: 20px;
            margin-top: 20px;
        }
        .code-editor-container {
            flex: 1;
            border: 1px solid #ddd;
            border-radius: 4px;
            min-height: 400px;
            position: relative;
            overflow: hidden;
        }
        #code-editor {
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            font-size: 16px !important; /* 确保字体大小合适 */
        }
        .preview-pane {
            flex: 1;
            border: 1px solid #ddd;
            border-radius: 4px;
            padding: 10px;
            overflow: auto;
            min-height: 400px;
            display: flex;
            align-items: center;
            justify-content: center;
            background-color: #f8f9fa;
        }
        .mermaid-toolbar {
            margin-bottom: 10px;
            display: flex;
            justify-content: space-between;
            padding: 10px 0;
            border-bottom: 1px solid #eee;
        }
        .alert-container {
            position: fixed;
            top: 20px;
            right: 20px;
            z-index: 2000;
            min-width: 300px;
        }
        .loading-overlay {
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: rgba(255, 255, 255, 0.9);
            display: flex;
            align-items: center;
            justify-content: center;
            z-index: 100;
        }
        .empty-preview {
            color: #6c757d;
            text-align: center;
            padding: 20px;
        }
        
        /* 新增：确保编辑器可见 */
        .ace_editor {
            position: relative !important;
            height: 100% !important;
            width: 100% !important;
        }
    </style>
{% endblock %}

{% block content %}
<div class="container mt-4">
    <div class="alert-container" id="alert-container"></div>
    
    <div class="d-flex justify-content-between align-items-center mb-4">
        <h2>{{ title }}</h2>
        <div>
            <button class="btn btn-outline-secondary" id="help-btn">
                <i class="bi bi-question-circle"></i> 帮助
            </button>
        </div>
    </div>
    
    <div class="card">
        <div class="card-body">
            <div class="mb-4">
                <label class="form-label fw-bold">图表标题</label>
                <input type="text" id="diagram-title" class="form-control form-control-lg" 
                       value="{{ diagram.title if diagram else '未命名图表' }}" 
                       placeholder="请输入图表标题">
            </div>
            
            <div class="mermaid-toolbar">
                <div class="btn-group">
                    <button class="btn btn-primary" id="preview-btn">
                        <i class="bi bi-eye me-1"></i> 预览图表
                    </button>
                    <button class="btn btn-success" id="save-btn">
                        <i class="bi bi-save me-1"></i> 保存图表
                    </button>
                </div>
                <div>
                    <button class="btn btn-outline-danger" id="reset-btn">
                        <i class="bi bi-arrow-counterclockwise"></i> 重置
                    </button>
                </div>
            </div>
            
            <div class="editor-container">
                <div class="code-editor-container" style="height: 100%;">
                    <div id="code-editor"></div>
                    <div class="loading-overlay" id="editor-loading">
                        <div class="text-center">
                            <div class="spinner-border text-primary" role="status"></div>
                            <p class="mt-2">编辑器加载中...</p>
                        </div>
                    </div>
                </div>
                <div id="preview-pane" class="preview-pane">
                    <div class="empty-preview">
                        <i class="bi bi-diagram-3" style="font-size: 3rem;"></i>
                        <h5 class="mt-3">图表预览区</h5>
                        <p class="text-muted">编辑Mermaid代码后，点击"预览图表"按钮查看效果</p>
                        <button class="btn btn-outline-primary mt-2" id="initial-preview-btn">
                            <i class="bi bi-eye me-1"></i> 点击预览
                        </button>
                    </div>
                </div>
            </div>
            
            <div class="mt-4">
                <div class="d-flex justify-content-between align-items-center mb-2">
                    <h5>Mermaid 语法参考</h5>
                    <a href="https://mermaid.js.org/syntax/entityRelationshipDiagram.html" 
                       target="_blank" class="btn btn-sm btn-link">
                        完整文档 <i class="bi bi-box-arrow-up-right"></i>
                    </a>
                </div>
                <div class="card">
                    <div class="card-body">
                        <pre id="syntax-help" class="p-3 bg-light rounded"></pre>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
    // 在DOM加载完成后初始化编辑器
    document.addEventListener('DOMContentLoaded', function() {
        // 获取CSRF令牌
        const csrfToken = "{{ csrf_token() }}";

        // 存储初始数据
        const initData = {
            id: (function() {
                try {
                    return JSON.parse("{{ diagram.id if diagram else 'null' }}");
                } catch (e) {
                    return undefined;
                }
            })(),
            req_id: "{{ req_id }}",
            type: "{{ diagram_type }}",
            title: "{{ diagram.title if diagram else '' }}",
            mermaid_code: "{{ diagram.mermaid_code if diagram else '' }}",
        };

        // 显示提示消息
        function showAlert(message, type = 'success') {
            const alertContainer = document.getElementById('alert-container');
            const alert = document.createElement('div');
            alert.className = `alert alert-${type} alert-dismissible fade show`;
            alert.innerHTML = `
                ${message}
                <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
            `;
            alertContainer.appendChild(alert);
            
            // 自动关闭
            setTimeout(() => {
                alert.remove();
            }, 5000);
        }

        // 初始化Mermaid
        mermaid.initialize({ 
            startOnLoad: false,
            theme: 'default',
            securityLevel: 'loose',
            fontFamily: 'Arial, sans-serif'
        });
            
        // 初始化编辑器
        let editor;
            
        function initEditor() {
            // 显示加载状态
            document.getElementById('editor-loading').classList.remove('d-none');
                
            try {
                    // 创建Ace编辑器
                    editor = ace.edit("code-editor");
                    editor.setTheme("ace/theme/chrome");
                    editor.session.setMode("ace/mode/text");
                    editor.setFontSize(16);
                    editor.setOptions({
                        enableBasicAutocompletion: true,
                        enableLiveAutocompletion: true,
                        enableSnippets: true,
                        showPrintMargin: false,
                        highlightActiveLine: true,
                        showLineNumbers: true,
                        showGutter: true
                    });
                    
                    // 设置初始代码
                    if (initData.mermaid_code && initData.mermaid_code.trim() !== '') {
                        editor.setValue(initData.mermaid_code);
                    } else {
                        // 根据类型设置模板
                        const template = getTemplateByType(initData.type);
                        editor.setValue(template);
                    }
                    
                    editor.clearSelection();
                    editor.gotoLine(0);
                    
                    // 调整编辑器大小以适应容器
                    editor.resize();
                    
                    // 隐藏加载状态
                    document.getElementById('editor-loading').classList.add('d-none');
                    
                    // 初始预览（延迟执行）
                    setTimeout(() => {
                        previewDiagram();
                    }, 300);
                    
                } catch (error) {
                    console.error('编辑器初始化失败:', error);
                    document.getElementById('editor-loading').innerHTML = `
                        <div class="alert alert-danger">
                            <h5><i class="bi bi-exclamation-triangle"></i> 编辑器加载失败</h5>
                            <p>请检查网络连接并刷新页面</p>
                        </div>
                    `;
                }
            }
            
            // 预览图表
            function previewDiagram() {
                const code = editor.getValue();
                const previewPane = document.getElementById('preview-pane');
                
                // 清除旧内容
                previewPane.innerHTML = '';
                
                // 渲染新图表
                try {
                    mermaid.render('mermaid-preview', code, (svgCode) => {
                        previewPane.innerHTML = svgCode;
                    });
                } catch (e) {
                    previewPane.innerHTML = `<div class="alert alert-danger">渲染错误: ${e.message}</div>`;
                }
            }
            
            // 保存图表
            document.getElementById('save-btn').addEventListener('click', function() {
                const diagramData = {
                    id: initData.id,
                    req_id: initData.req_id,
                    type: initData.type,
                    title: document.getElementById('diagram-title').value,
                    code: editor.getValue()
                };
                
                // 发送保存请求
                fetch("{{ url_for('diagram.save_diagram') }}", {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'X-CSRFToken': csrfToken  // 使用统一的CSRF令牌
                    },
                    body: JSON.stringify(diagramData)
                })
                .then(response => {
                    if (!response.ok) {
                        throw new Error(`HTTP错误! 状态: ${response.status}`);
                    }
                    return response.json();
                })
                .then(data => {
                    if (data.status === 'success') {
                        // 更新ID以便后续编辑
                        if (data.id) initData.id = data.id;
                        
                        showAlert('图表保存成功!', 'success');
                        
                        // 自动关闭窗口（可选）
                        setTimeout(() => {
                            if (window.opener && !window.opener.closed) {
                                window.opener.location.reload();
                            }
                            window.close();
                        }, 2000);
                    } else {
                        throw new Error(data.message || '服务器返回未知错误');
                    }
                })
                .catch(error => {
                    console.error('保存失败:', error);
                    showAlert(`保存失败: ${error.message}`, 'danger');
                });
            });
            
            // 初始化编辑器
            initEditor();
            
            // 语法帮助
            document.getElementById('syntax-help').textContent = 
                initData.type === 'erd' ? `erDiagram\n    ENTITY1 {\n        type field1 PK\n        type field2\n    }\n    ENTITY2 {\n        type field3 PK\n        type field4\n    }\n    \n    ENTITY1 ||--o{ ENTITY2 : \"关系描述\"` : 
                initData.type === 'sequence' ? `sequenceDiagram\n    participant A as 参与者A\n    participant B as 参与者B\n    A->>B: 请求消息\n    B-->>A: 响应消息` : 
                `flowchart TD\n    A[开始] --> B{条件}\n    B -->|是| C[执行操作]\n    B -->|否| D[操作2]`;
        });
    </script>
{% endblock %}